<template>
  <div class="common-body">
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      state="detail"
      @handleBack="handleBack"
    />

    <div
      v-if="isTrue"
      :class="[
        contractState ? 'ccui-app-container-detail' : 'detail-box',
        'ccui-clearfix'
      ]"
    >
      <!--  主体左侧内容  -->
      <div :class="[!contractState ? 'detail-info' : '']">
        <!--  审批状态 icon  -->
        <div v-if="!contractState" class="detail-info-el-Label">
          <el-label :type="approving" v-if="approvingStatus"></el-label>
        </div>
        <div
          :class="[
            !contractState
              ? 'detail-info-form-container'
              : 'ccui-app-container-detail-body'
          ]"
        >
          <el-tabs v-model="activeName" class="el-tabs__customize">
            <el-tab-pane label="基本信息" name="first">
              <detailBaseInfo
                ref="baseInfo"
                labelWidth="130px"
                :formList="baseFormList"
                :detail="detailInfo.smpPcConc"
                :highlightArr="baseHighlightArr"
              />
            </el-tab-pane>

            <el-tab-pane label="财务信息" name="second">
              <financeInfo
                isChange
                :detail="detailInfo.pcFinance || {}"
                :highlightArr="financeHighlightArr"
              />
            </el-tab-pane>

            <el-tab-pane label="采购清单" name="third">
              <oneLineTable
                ref="purchaseList"
                showSummary
                :summaryArr="summaryArr"
                :tableTheadOptions="baseJsObj.purchaseTableThead"
                :oneLineTableData="detailInfo.smpConcMatLessList"
                :highlightRow="highlightRow"
              />
            </el-tab-pane>

            <el-tab-pane label="使用范围" name="fourth">
              <oneLineTable
                ref="useRange"
                :tableTheadOptions="baseJsObj.useRangeTableThead"
                :oneLineTableData="detailInfo.smpUsableRange"
                :highlightRow="highlightRow"
              />
            </el-tab-pane>

            <el-tab-pane label="付款方式" name="fifth">
              <paymentMode ref="paymentMode" :detail="detailInfo" />
            </el-tab-pane>

            <el-tab-pane label="合同附件" name="sixth">
              <contractAnnex
                ref="contractAnnex"
                isTab
                v-model="uploadList"
                state="detail"
              />
            </el-tab-pane>

            <el-tab-pane label="变更历史" name="seventh">
              <oneLineTable
                ref="histryChanges"
                :highlightNodeArr="['contractCode']"
                :tableTheadOptions="baseJsObj.histryChangeTableThead"
                :oneLineTableData="detailInfo.oldSmpPcConcList"
                @gotoDetail="gotoDetail"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <!--  右边审批状态  -->
      <approvalReadRecord
        v-if="!contractState"
        :approvalRecordData="approvalRecordData"
      />
    </div>

    <!--  底部导航栏及签名导出  -->
    <bottomGuide
      v-if="isTrue"
      busiType="100"
      pageType="smppcconc/detailExport"
      :approvalStatus="approving"
      :curPageId="$route.params.id"
      :businessCode="businessCode"
      @handleBack="handleBack"
    />
  </div>
</template>

<script>
import jsObj from "../js";
import baseJsObj from "@/app/contractManagement/materialContract/contractDraft/js";
import { cloneDeep } from "lodash";
import { getSmpPcConcById } from "../api";
import contractComponent from "@/app/contractManagement/components";
import publicComponent from "@/basa/components/public";
import Mixin from "../mixins";
import { proxyDateFormat } from "@/basa/utils";

export default {
  mixins: [Mixin],
  components: {
    detailBaseInfo: publicComponent.detailBaseInfo,
    oneLineTable: publicComponent.oneLineTable,
    contractAnnex: contractComponent.changeUploadInfo,
    approvalReadRecord: publicComponent.approvalRecord,
    breadcrumb: publicComponent.breadcrumb,
    bottomGuide: publicComponent.bottomGuide,
    financeInfo: contractComponent.detailFinanceInfo,
    paymentMode: contractComponent.detailPaymentMode
  },
  data() {
    return {
      jsObj,
      baseJsObj,
      breadcrumbLastItem: "",
      businessCode: "",
      isTrue: false,
      detailInfo: {},
      activeName: "first",
      tabStyle: {},
      contractState: "",
      approvalRecordData: [],
      approving: "", // 审批状态
      approvingStatus: true, // 审批状态展示
      approvingType: {
        0: "pending", //待审批
        1: "approving", // 审批中
        3: "approvaled", // 审批通过
        4: "sendback", // 已退回
        2: "withdrawn" // 已撤回
      },
      summaryArr: [
        "currentNum",
        "currentChangeAmtExcludeTax",
        "currentChangeAmtIncludeTax"
      ],
      uploadList: [],
      baseFormList: [],
      baseHighlightArr: [], // 基础信息高亮
      financeHighlightArr: [], // 财务信息高亮
      highlightRow: {}, // 清单信息高亮
      breadcrumbArr: []
    };
  },
  activated() {
    this.getSmpPcConcInfo();
    this.setBreadcrumb();
  },
  methods: {
    // 详情请求
    getSmpPcConcInfo() {
      const { id } = this.$route.params;
      const data = { concId: id, isShowWorkflow: 1 };
      getSmpPcConcById(data)
        .then(res => {
          const {
            data: { data }
          } = res;

          // 获取businessCode
          this.businessCode = data.smpPcConc.contractCode;

          // 使用范围时间处理
          data.smpUsableRange = data.smpUsableRange.map(n => ({
            ...n,
            operationTimeStr: n.operationTime
              ? proxyDateFormat(n.operationTime)
              : ""
          }));

          const jsFormList = cloneDeep(jsObj.baseFormList);
          // 币种判断
          if (data.smpPcConc.currencyName === "人民币") {
            const i = jsFormList.findIndex(
              _ => _.titleContent === "chExchangeRate"
            );
            jsFormList.splice(i, 1);
            const j = jsFormList.findIndex(
              _ => _.titleContent === "exchangeRateRefDate"
            );
            jsFormList.splice(j, 1);
          }
          // 兑美元美元汇率
          if (
            data.smpPcConc.isOverseas !== 3 &&
            !["人民币", "美元"].includes(data.smpPcConc.currencyName)
          ) {
            const i = jsFormList.findIndex(
              _ => _.titleContent === "currencyName"
              // _ => _.titleContent === "initTotalContractPriceIncludeTax"
            );
            jsFormList.splice(i, 0, {
              label: "兑美元汇率",
              titleContent: "usExchangeRate"
            });
          }
          // 多税率判断
          if (data.smpPcConc.multiRateCode === 0) {
            const i = jsFormList.findIndex(
              _ => _.titleContent === "taxRatePercent"
            );
            jsFormList.splice(i, 1);
          }

          // 是否浮动合同价格判断
          if (data.smpPcConc.isFloatContractPrice === 1) {
            const i = jsFormList.findIndex(_ => _.titleContent === "floatDesc");
            jsFormList.splice(i, 1);
          }
          this.baseFormList = jsFormList;

          // 基础信息处理
          data.smpPcConc = {
            ...data.smpPcConc,
            // 时间处理
            compileDateStr: data.smpPcConc.compileDate
              ? proxyDateFormat(data.smpPcConc.compileDate)
              : "",
            exchangeRateRefDate: data.smpPcConc.exchangeRateRefDate
              ? proxyDateFormat(data.smpPcConc.exchangeRateRefDate)
              : "",
            // 价格
            initTotalContractPriceIncludeTax:
              data.smpPcConc.initTotalContractPriceIncludeTax !== null
                ? data.smpPcConc.initTotalContractPriceIncludeTax.toFixed(2)
                : "",
            initTotalConractPriceExcludeTax:
              data.smpPcConc.initTotalConractPriceExcludeTax !== null
                ? data.smpPcConc.initTotalConractPriceExcludeTax.toFixed(2)
                : "",
            // 是否浮动合同价格
            isFloatContractPrice: baseJsObj.whetherList.find(
              _ => _.dicKey === data.smpPcConc.isFloatContractPrice
            ).dicValue,
            // 是否海外采购
            isOverseas: baseJsObj.isOverseasList.find(
              _ => _.value === data.smpPcConc.isOverseas
            ).label,
            // 多税率
            multiRateCode:
              data.smpPcConc.multiRateCode !== null
                ? baseJsObj.whetherList.find(
                    _ => _.dicKey === data.smpPcConc.multiRateCode
                  ).dicValue
                : ""
          };

          // 采购清单处理
          if (data.smpConcMatLessList.length) {
            data.smpConcMatLessList = data.smpConcMatLessList.map(n => ({
              ...n,
              deliveryTime: n.deliveryTime
                ? proxyDateFormat(n.deliveryTime)
                : "",
              currentNum: n.currentNum !== null ? n.currentNum.toFixed(3) : "",
              currentUnitPriceExcludeTax:
                n.currentUnitPriceExcludeTax !== null
                  ? n.currentUnitPriceExcludeTax.toFixed(2)
                  : "",
              currentChangeAmtExcludeTax:
                n.currentChangeAmtExcludeTax !== null
                  ? n.currentChangeAmtExcludeTax.toFixed(2)
                  : "",
              currentUnitPriceIncludeTax:
                n.currentUnitPriceIncludeTax !== null
                  ? n.currentUnitPriceIncludeTax.toFixed(2)
                  : "",
              currentChangeAmtIncludeTax:
                n.currentChangeAmtIncludeTax !== null
                  ? n.currentChangeAmtIncludeTax.toFixed(2)
                  : "",
              rate: n.rate !== null ? n.rate.toFixed(2) : "",
              address:
                (n.deliveryAreaName || "") +
                (n.provinceName || "") +
                (n.cityName || "") +
                (n.countyName || "") +
                (n.deliveryPoints || "") // 交货地点
            }));
          }

          // 过滤附件
          this.uploadList = data.concFiles.filter(_ =>
            ["1", "2", "3"].includes(_.businessSonType)
          );

          // 处理变更历史
          if (data.oldSmpPcConcList.length) {
            data.oldSmpPcConcList = data.oldSmpPcConcList.map(n => ({
              ...n,
              compileDateStr: n.compileDate
                ? proxyDateFormat(n.compileDate)
                : ""
            }));
          }

          // 付款方式处理
          data.payTypeListBOS = data.payTypeListBOS.map(n => ({
            smpPayTypeBO: {
              ...n.smpPayTypeBO,
              highlightFlag: 1
            },
            smpPayTypeItemBOS: n.smpPayTypeItemBOS.map(m => ({
              ...m,
              highlightFlag: 1
            }))
          }));

          this.baseHighlightArr = data.smpPcConc.changeFieldsArray; // 基础高亮的字段
          this.financeHighlightArr = data.pcFinance.changeFieldsArray; // 财务高亮的字段
          this.highlightRow = { key: "isChangeFlag", value: 1 }; // 清单信息高亮

          this.breadcrumbLastItem = data.smpPcConc.contractName;
          this.approving = this.approvingType[data.smpPcConc.checkState];

          // 赋值
          data.smpPcConc = Object.assign(
            data.smpPcConc,
            data.pcFinance[0] || {}
          );
          this.detailInfo = Object.assign(data, {
            state: "detail"
          });
          this.contractState = !data.approveRecords.length;
          this.approvalRecordData = data.approveRecords;
          this.approvingStatus = false;
          this.isTrue = true;
          this.$nextTick(() => {
            this.approvingStatus = true;
          });
        })
        .catch(e => {});
    },
    // 面包屑更改
    setBreadcrumb() {
      let breadcrumbArr = cloneDeep(jsObj.breadcrumbArr);
      if (this.$route.query.type == "approval") {
        breadcrumbArr[2] = {
          path: "/contractManagement/contractApproval/approvalList",
          text: "合同审批"
        };
      }
      this.breadcrumbArr = breadcrumbArr;
    },
    gotoDetail({ id }) {
      this.$router.push(`/contractManagement/contractChange/item-detail/${id}`);
    }
  }
};
</script>
